package com.zzy.socket.nio_socket_channel;

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * 1.通过SocketChannel连接到远程服务器 2.创建读数据/写数据缓冲区对象来读取服务端数据或向服务端发送数据 3.关闭SocketChannel
 * 
 * @author guokaige
 *
 */
public class NioSocketChannelClient {
	
	public static void main(String[] args) throws IOException {
		// 1.通过SocketChannel的open()方法创建一个SocketChannel对象
		SocketChannel socketChannel = SocketChannel.open();

		// 2.连接到远程服务器（连接此通道的socket）
		socketChannel.connect(new InetSocketAddress("127.0.0.1", 3333));

		// 3.创建写数据缓存区对象
		ByteBuffer writeBuffer = ByteBuffer.allocate(128);
		writeBuffer.put("客户端:-----------------发消息-------------------:你好! (来自客户端)".getBytes("UTF-8"));
		writeBuffer.flip();
		socketChannel.write(writeBuffer);

		// 创建读数据缓存区对象
		ByteBuffer readBuffer = ByteBuffer.allocate(128);
		socketChannel.read(readBuffer);
		// String 字符串常量，不可变；StringBuffer 字符串变量（线程安全），可变；StringBuilder 字符串变量（非线程安全），可变
		StringBuilder stringBuffer = new StringBuilder();
		// 4.将Buffer从写模式变为可读模式
		readBuffer.flip();
		while (readBuffer.hasRemaining()) {
			stringBuffer.append((char) readBuffer.get());
		}
		System.out.println("客户端:-----------------收消息-------------------：" + stringBuffer);
		socketChannel.close();
	}
}